package servlets;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 本Servlet生成一个4位数的随机码图片的响应，用在登录页面。
 * 每次刷新本Servlet都将产生一个新的随机码，每次生成的正确的随机码保存在Session对象中，具体见下面的代码。
 */
@WebServlet(urlPatterns="/randomNumber.do")
public class RandomNumberServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RandomNumberServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置内容类型
		response.setContentType("image/jpg");
		response.setDateHeader("expries", -1);
	    response.setHeader("Cache-Control", "no-cache");
	    response.setHeader("Pragma", "no-cache");
	    String randomCode = generateRandomNum();
	    //将随机码作为登录验证码保存在session中
	    request.getSession().setAttribute("checkCode", randomCode);
	    //将图片写入到response输出流
	    ImageIO.write(generateImg(randomCode), "jpg", response.getOutputStream());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	/**
	 * 生成一张图片，并将随机码写入到图片中。
	 * @param randomCode 随机码
	 * @return 图片对象
	 */
	private BufferedImage generateImg(String randomCode){
		BufferedImage bufferedImage = new BufferedImage(50, 20, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = (Graphics2D)bufferedImage.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 50, 20);
        g.setColor(Color.RED);
        g.setFont(new Font(null, Font.BOLD, 20));
        g.drawString(randomCode, 0, 20);
        return bufferedImage;
	}
	/**
	 * 生成4位数随机码
	 * @return 随机码字符串
	 */
	private String generateRandomNum() {
		Random random = new Random();
		String num = String.valueOf(random.nextInt(9999));
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 4 - num.length(); i++) {
			sb.append("0");
		}
		num = sb.toString() + num;
		return num;
	}

}
